#!/usr/bin/env python3
# coding: utf-8
# File: GraphShow.py
from neo4j import GraphDatabase

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "0813Ztcg"))


class Intoneo4j():
    # 添加文章节点边到neo4j数据库中
    def add_article(self,tx, first_node, second_node):
        tx.run("MERGE (a:Article {node: $first_node}) "
               "MERGE (a)-[:指向]->(refers:Article {node: $second_node})",
               first_node=first_node, second_node=second_node)

    # 打印节点所属节点的信息
    def print_article(self,tx, first_node):
        for record in tx.run("MATCH (a:Article)-[:指向]->(refers) WHERE a.node = $first_node "
                             "RETURN refers.node ORDER BY refers.node", first_node=first_node):
            print(record["refers.node"])

    def create_neo4j(self, events):
        nodes = []
        for event in events:
            nodes.append(event[0])
            nodes.append(event[1])
        node_dict = {node: index for index, node in enumerate(nodes)}
        # 声明数组用来保存所有节点信息
        data_nodes = []
        # 声明数组用来保存所有关系信息
        data_edges = []
        # 遍历添加节点数据
        for node, id in node_dict.items():
            data = {}
            data["id"] = id
            data["label"] = node
            data_nodes.append(data)
        # 遍历添加关系数据
        for edge in events:
            data = {}
            data["from"] = node_dict.get(edge[0])
            data["label"] = "指向"
            data["to"] = node_dict.get(edge[1])
            data_edges.append(data)
        # 双重遍历判断条件
        for node in data_nodes:
            for edge in data_edges:
                if node['id'] == edge['from']:
                    edge['from'] = node['label']
                if node['id'] == edge['to']:
                    edge['to'] = node['label']
        with driver.session() as session:
            for edge in data_edges:
                session.write_transaction(self.add_article, edge['from'], edge['to'])